// pages/order_list/order_list.js
const util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    toView: '',
    searchNum: '',
    orderList: [],
    startDate: '',
    endDate: '',
    nickname: '',
    addr: '',
    courier: ['选择快递公司','顺丰','EMS']
  },
  getUrlParam: function(name, url) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
    let result = url.substr(1).match(reg)
    return result ? decodeURIComponent(result[2]) : null
  },
  changeStartDate: function (e) {
    let that = this
    let startDate = e.detail.value
    that.setData({
      startDate: startDate
    })
    that.onLoad()
  },
  changeEndDate: function (e) {
    let that = this
    let endDate = e.detail.value
    that.setData({
      endDate: endDate
    })
    that.onLoad()
  },
  changeNickname: function (e) {
    let that = this
    let nickname = e.detail.value
    that.setData({
      nickname: nickname
    })
    that.onLoad()
  },
  changeAddr: function (e) {
    let that = this
    let addr = e.detail.value
    that.setData({
      addr: addr
    })
    that.onLoad()
  },
  bindCourierChange: function (e) {
    console.log(e)
    let that = this
    let index = e.currentTarget.dataset.index
    let item = e.currentTarget.dataset.item
    let allOrder = that.data.orderList
    let selectCourier = e.detail.value

    for (let i = 0; i < allOrder.length; i++) {
      allOrder[index].courierCompany = selectCourier
    }
    console.log(allOrder)
    that.setData({
      orderList: allOrder
    })
    
  },
  setExpress: function (e) {
    let that = this
    let express = e.detail.value
    let index = e.currentTarget.dataset.index
    let item = e.currentTarget.dataset.item
    let allOrder = that.data.orderList

    for (let i = 0; i < allOrder.length; i++) {
      allOrder[index].express = express
    }
    that.setData({
      orderList: allOrder
    })
  },
  toSaveNum: function (e) {
    let that = this
    let order_num = e.currentTarget.dataset.order_num
    let express = e.currentTarget.dataset.express
    let courier = e.currentTarget.dataset.courier
    let courierCompany = that.data.courier[courier]

    if (courier == 0) {
      wx.showToast({
        title: '请选择快递公司',
        icon: 'none',
        duration: 3000
      })
      return false
    }

    if (express == '' || express == 'undefined' || express == undefined) {
      wx.showToast({
        title: '请填写快递单号',
        icon: 'none',
        duration: 3000
      })
      return false
    }

    let express_msg = courierCompany+'|'+express

    wx.showLoading({
      title: '正在修改快递单号',
    })
    util.request('V2/commitExpress',
      {
        order_num: order_num,
        express_msg: express_msg
      },
      function (res) {
        console.log(res)
        wx.hideLoading()
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'none',
            duration: 3000,
            success: function(res) {
              that.onLoad()
            }
          })
          
        } else if (res.data.code < 0) {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        }
      },
      function (res) {
        //尝试重启
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          success: function (result) {
            if (result.confirm) {
              wx.reLaunch({
                url: '../login/login'
              })
            }
          }
        })

      },
      function (res) {
        wx.hideLoading();
      }
    )
  },
  toScanCode: function (e) {
    let that = this
    that.isFromScan = true
    let index = e.currentTarget.dataset.index
    let courier = e.currentTarget.dataset.courier
    let item = e.currentTarget.dataset.item
    let allOrder = that.data.orderList
    console.log(courier)
    // return false
    wx.scanCode({
      success: (res) => {
        console.log("扫码成功")
        console.log(res)
        let scanResult = res.result

        let code = ''
        if (courier == 1) {
          let toArr = '?'+scanResult.split('?')[1]
          code = that.getUrlParam('p1', toArr)
        } else if(courier == 2) {
          code = scanResult
        }else{
          let toArr = '?' + scanResult.split('?')[1]
          code = that.getUrlParam('p1', toArr)
        }

        for (let i = 0; i < allOrder.length; i++) {
          allOrder[index].express = code
          // allOrder[index].express_msg = code
        }
        console.log(allOrder)
        that.setData({
          orderList: allOrder
        })
        return false
      },
      fail: (res) => {
        console.log("扫码失败")
        console.log(res)
      }
    })
  },
  onCancel: function(e) {
    let that = this
    that.setData({
      searchNum: ''
    })
  },
  onConfirm: function (e) {
    console.log(e)
    let that = this
    let loginStatus = util.getUserdata('loginStatus')
    if (!loginStatus.isLogin) {
      wx.showModal({
        title: '提示',
        content: '检测帐号未登录,请进行登录',
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '../login/login'
            })
          }
        }
      })
      return false
    }

    let orderNumber = e.detail.value
    let startDate = that.data.startDate
    let endDate = that.data.endDate
    let nickname = that.data.nickname
    let addr = that.data.addr
    console.log(orderNumber)
    console.log(startDate)
    console.log(endDate)
    console.log(nickname)
    console.log(addr)

    wx.showLoading({
      title: '正在查询',
    })
    util.request('V1/operatorOrder',
      {
        order_num: orderNumber,
        startDate: startDate + ' 00:00:00',
        endDate: endDate+' 23:59:59',
        nickname: nickname,
        addr: addr
        // order_num: '2019082210248100'
      },
      function (res) {
        console.log(res)
        wx.hideLoading()
        if (res.data.code == 200) {
          let rtn = res.data.order_list
          for(let i = 0; i < rtn.length; i++) {
            let temp = rtn[i].express_msg.split('|')
            rtn[i].courierCompany = temp[0] == '顺丰' || temp[0] == '' ? '1' : '2'
            rtn[i].express = temp[1]
            rtn[i].obj_modifydate = util.date_time(rtn[i].obj_modifydate, 'Y-M-D h:m:s')
          }

          let toViewOrder = 'L'+rtn[0].order_num

          that.setData({
            orderList: rtn,
            toView: toViewOrder
          })
        } else if (res.data.code < 0){
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        }
      },
      function (res) {
        //尝试重启
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          success: function (result) {
            if (result.confirm) {
              wx.reLaunch({
                url: '../login/login'
              })
            }
          }
        })

      },
      function (res) {
        wx.hideLoading();
      }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onload')

    let that = this
    let startDate = that.data.startDate || util.formatTime(new Date())
    let endDate = that.data.endDate || util.formatTime(new Date())
    let nickname = that.data.nickname
    let addr = that.data.addr
    that.setData({
      startDate: startDate,
      endDate: endDate,
      nickname: nickname,
      addr: addr
    })

    let loginStatus = util.getUserdata('loginStatus')
    if (!loginStatus.isLogin) {
      wx.showModal({
        title: '提示',
        content: '检测帐号未登录,请进行登录',
        success: function(res) {
          if(res.confirm) {
            wx.switchTab({
              url: '../login/login'
            })
          }
        }
      })
      return false
    }

    wx.showLoading({
      title: '正在查询',
    })
    console.log(nickname)
    util.request('V1/operatorOrder',
      {
        order_num: '',
        startDate: startDate + ' 00:00:00',
        endDate: endDate + ' 23:59:59',
        nickname: nickname,
        addr: addr
        // order_num: '2019082210248100'
      },
      function (res) {
        console.log(res)
        wx.hideLoading()
        if (res.data.code == 200) {
          let rtn = res.data.order_list
          for (let i = 0; i < rtn.length; i++) {
            let temp = rtn[i].express_msg.split('|')
            rtn[i].courierCompany = temp[0] == '顺丰' || temp[0] == '' ? '1' : '2'
            rtn[i].express = temp[1]
            rtn[i].obj_modifydate = util.date_time(rtn[i].obj_modifydate, 'Y-M-D h:m:s')
          }
          console.log(rtn)

          that.setData({
            orderList: rtn
          })
        } else if (res.data.code < 0) {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success: function (result) {
              if (result.confirm) {
              }
            }
          })
        }
      },
      function (res) {
        //尝试重启
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          success: function (result) {
            if (result.confirm) {
              wx.reLaunch({
                url: '../login/login'
              })
            }
          }
        })

      },
      function (res) {
        wx.hideLoading();
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onshow')
    let that = this
    if (that.isFromScan) { that.isFromScan = false; return }
    let loginStatus = util.getUserdata('loginStatus')
    console.log(loginStatus.isLogin)
    if (loginStatus.isLogin == true) {
      that.setData({
        isLogin: true
      })
      that.onLoad()
    }else{
      that.setData({
        isLogin: false
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('onUnload')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.onLoad()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})